package weixin

import (
	"bytes"
	"encoding/json"
	"errors"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model"
	"io"
	"net/http"
	"time"
)

type AccessToken struct {
	ID           uint `gorm:"primarykey;->"`
	Platform     string
	Appid        string
	Secret       string
	Access_token string
	Expires_time string
	model.BaseTime
}

func AccessTokenGet() (string, error) {

	var one AccessToken
	if err := bean.MysqlDb.Model(&AccessToken{}).Where("id=?", 1).First(&one).Error; err != nil {
		return "", err
	}

	var expireTime, err = time.ParseInLocation(time.DateTime, one.Expires_time, time.Local)
	if err != err {
		return "", err
	}

	if time.Now().Before(expireTime) {
		return one.Access_token, nil
	}

	var req struct {
		Grant_type string `json:"grant_type"`
		Appid      string `json:"appid"`
		Secret     string `json:"secret"`
	}

	req.Grant_type = "client_credential"
	req.Appid = one.Appid
	req.Secret = one.Secret

	jsonValue, err := json.Marshal(req)
	if err != nil {
		return "", err
	}

	// 将JSON数据写入请求的body中
	requestBody := bytes.NewBuffer(jsonValue)

	// 创建请求
	request, err := http.NewRequest("POST", "https://api.weixin.qq.com/cgi-bin/stable_token", requestBody)
	if err != nil {
		return "", err
	}

	// 设置Header
	request.Header.Set("Content-Type", "application/json")

	// 执行请求
	client := &http.Client{}
	response, err := client.Do(request)
	if err != nil {
		return "", err
	}

	defer response.Body.Close()

	// 读取响应
	body, err := io.ReadAll(response.Body)
	if err != nil {
		return "", err
	}

	var resp struct {
		Errcode      uint   `json:"errcode"`
		Access_token string `json:"access_token"`
		Expires_in   uint   `json:"expires_in"`
	}

	err = json.Unmarshal(body, &resp)
	if err != nil {
		return "", err
	}

	//
	if resp.Errcode != 0 {
		return "", errors.New(string(body))
	}

	// 更新数据
	var two AccessToken
	two.ID = 1
	two.Access_token = resp.Access_token
	two.Expires_time = time.Now().Add(time.Second * time.Duration(resp.Expires_in-1000)).Format(time.DateTime)

	if err := bean.MysqlDb.Updates(&two).Error; err != nil {
		return "", err
	}

	return two.Access_token, nil
}
